package com.szqhyxj.youxiangju.biz.realNameAuth.bankcard;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.szqhyxj.youxiangju.biz.core.ImageUploadResult;
import com.szqhyxj.youxiangju.biz.core.ImageUploader;
import com.szqhyxj.youxiangju.biz.core.UserInfo;
import com.szqhyxj.youxiangju.biz.core.UserInfoManger;
import com.szqhyxj.youxiangju.biz.core.UserInfoModel;
import com.szqhyxj.youxiangju.biz.realNameAuth.RealNameModel;
import com.szqhyxj.youxiangju.sys.BaseResult;
import com.szqhyxj.youxiangju.sys.util.BitmapCompressFile;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by leung on 2018/10/31.
 */

public class BankCardPresenter implements BankCardAuthContract.Presenter {

    BankCardAuthContract.View view;

    BankCardEntity bankCardEntity;

    private List<Disposable> disposables = new ArrayList<>();

    private RealNameMsmEntity realNameMsmEntity;

    public BankCardPresenter(BankCardAuthContract.View view) {
        this.view = view;
        this.bankCardEntity = new BankCardEntity();
        realNameMsmEntity = new RealNameMsmEntity();
    }

    @Override
    public void setusername(String s) {
        bankCardEntity.setUsername(s);
        checkRegisterEnable();
    }

    @Override
    public void setbankCardNo(String s) {
        bankCardEntity.setBankCardNo(s);
        checkRegisterEnable();
    }

    @Override
    public void setbtCode(String s) {
        bankCardEntity.setBtCode(s);
        checkRegisterEnable();
    }

    @Override
    public void setbtName(String s) {
        bankCardEntity.setBtName(s);
        checkRegisterEnable();
    }

    @Override
    public void setcardPhone(String s) {
        bankCardEntity.setCardPhone(s);
        checkRegisterEnable();
    }

    @Override
    public void setbankCardPic(String s) {
        bankCardEntity.setBankCardPic(s);
        checkRegisterEnable();
    }

    @Override
    public void setverCode(String s) {
        bankCardEntity.setVerCode(s);
        checkRegisterEnable();
    }

    private void checkRegisterEnable() {
        if (bankCardEntity.valid()) {
            view.showCommit();

        } else {
            view.showEnCommit();

        }
    }

    @Override
    public void commint() {
        view.showLoading();

        RealNameModel.Cardcommit(this.bankCardEntity)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResult>() {
                               @Override
                               public void accept(BaseResult baseResult) throws Exception {
                                   view.dismissLoading();
                                   if (baseResult.businessLogicSuccess()) {
                                       view.commitSuccess();
                                       getUserInfo();
                                   } else {
                                       view.commitFial(baseResult.getMessage());
                                   }

                               }
                           },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                view.dismissLoading();
                                view.commitFial(throwable.getMessage());
                            }
                        });
    }

    public void getUserInfo() {
        disposables.add(
                UserInfoModel.loadUserInfo()
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(
                                new Consumer<BaseResult<UserInfo>>() {
                                    @Override
                                    public void accept(BaseResult<UserInfo> baseResult) throws Exception {
                                        if (baseResult.businessLogicSuccess()) {
                                            UserInfoManger.INSTANCE.clear();
                                            UserInfoManger.INSTANCE.init(baseResult.getData());

                                        } else {
                                            view.commitFial(baseResult.getMessage());
                                        }
                                    }
                                },
                                new Consumer<Throwable>() {
                                    @Override
                                    public void accept(Throwable throwable) throws Exception {
                                        view.commitFial(throwable.getMessage());
                                    }
                                }));
    }

    @Override
    public void setPhone(String s) {
        realNameMsmEntity.setPhone(s);
        bankCardEntity.setCardPhone(s);
        checkRegisterEnable();

    }


    @Override
    public void takePhotoForCard(Context context) throws IOException {
        File faceFile = RealNameModel.createImageFile(context);
        this.bankCardEntity.setCard(faceFile);
        view.navToTakePhotoCard(faceFile);
    }

    @Override
    public void selectFromGalleryForCard() {
        view.navToGalleryForCard();
    }

    @Override
    public void idcardCardFromTakePhoto(Context context) throws IOException {
        view.previewBank(this.bankCardEntity.getCard());
        //  ocrIdcardCard(this.bankCardEntity.getCard());

    }

    @Override
    public void idcardCardFromGallery(File file) {
        view.previewBank(file);
        this.bankCardEntity.setCard(file);
        //  ocrIdcardCard(this.bankCardEntity.getCard());

    }

    @Override
    public void getIssuer() {
        RealNameModel
                .getBankList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<BaseResult<List<BankList>>>() {
                    @Override
                    public void accept(BaseResult<List<BankList>> bankListBaseResult) throws Exception {
                        if (bankListBaseResult.businessLogicSuccess()) {
                            if (bankListBaseResult.getData().size() == 0) {
                                view.showOcrFail("发卡行列表为空");
                            } else {
                                List<BankList> lists = bankListBaseResult.getData();
                                view.showIssuser(lists);
                            }

                        } else {
                            view.showOcrFail(bankListBaseResult.getMessage());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        view.showOcrFail(throwable.getMessage());
                    }
                });

    }

    private static final int MINUTE = 60;

    @Override
    public void acquireVerificationCode() {
        view.showLoading();
        disposables.add(RealNameModel.realNameSms(this.realNameMsmEntity)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<BaseResult>() {
                            @Override
                            public void accept(BaseResult baseResult) {
                                view.dismissLoading();
                                if (baseResult.businessLogicSuccess()) {
                                    view.showAcquiredVerificationCodeSuccess();
                                    view.showAcquiringVerificationCode(MINUTE);
                                    startCountDown();
                                } else {
                                    view.showToast(baseResult.getMessage());
                                }
                            }
                        },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                view.dismissLoading();
                                view.showToast(throwable.getMessage());
                            }
                        }
                )
        );
    }

    private void startCountDown() {
        disposables.add(Observable
                .interval(0, 1, TimeUnit.SECONDS)
                .take(MINUTE)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) {
                        if (aLong == MINUTE - 1) {
                            view.showAcquiredVerificationCode();
                        } else {
                            view.showAcquiringVerificationCode((int) (MINUTE - aLong - 1));
                        }
                    }
                }));
    }

    private void ocrIdcardCard(final File file) {
        view.showLoading("正在识别...");
        Disposable disposable = RealNameModel
                .ocrBankCard(file)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<BaseResult<CardInfo>>() {
                            @Override
                            public void accept(BaseResult<CardInfo> ocrResult) {
                                view.dismissLoading();
                                if (ocrResult.businessLogicSuccess()) {
                                    view.showbankCard(ocrResult.getData());
                                    view.showCardno(ocrResult.getData().getCardNo());
                                    view.enshowOCRTip();
                                    uploadBankCard();
                                } else {
                                    view.showBank();
                                    view.showOcrFail(ocrResult.getMessage());
                                    view.showOCRTip(ocrResult.getMessage());

                                }
                            }
                        },
                        new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                view.dismissLoading();
                                view.showBank();
                                view.showOCRTip(throwable.getMessage());
                                view.showOcrFail(throwable.getMessage());
                                view.showOCRTip(throwable.getMessage());

                            }
                        }
                );
        disposables.add(disposable);
    }

    @Override
    public void uploadBankCard() {

        if(bankCardEntity.getCard() == null){
            view.showToast("未提供储蓄卡照片");
            return;
        }
        File file =BitmapCompressFile.compressFile(bankCardEntity.getCard());
        view.showLoading("正在上传...");
        Disposable disposable = ImageUploader
                .uploadDeposit(file,bankCardEntity.getBankCardNo())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Consumer<BaseResult<ImageUploadResult>>() {
                            @Override
                            public void accept(BaseResult<ImageUploadResult> uploadResult) {
                                view.dismissLoading();
                                if (uploadResult.businessLogicSuccess()) {
                                    //  view.showBankCardUploadSuccess(uploadResult.getData().getFileUrl());
                                    bankCardEntity.setBankCardPic(uploadResult.getData().getFileUrl());
                                    commint();
                                    view.uploadSuccessCard();
                                } else {
                                    view.showBankCardUploadFail(uploadResult.getMessage());
                                }
                                file.delete();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) {
                                view.dismissLoading();
                                view.showBankCardUploadFail(throwable.getMessage());
                                file.delete();
                            }
                        }
                );
        disposables.add(disposable);
    }


}
